const registrationModel = require('../models/registrations.model')
const logger = require('../utils/logger')

class RegistrationService {
  registrations = registrationModel
  async findAll ({
    page = 1,
    pageSize = 100,
    reg_status,
    reg_xzxq,
    reg_dwmc,
    submitter,
    place
  }) {
    const query = {
      deleted: false
    }
    if (reg_dwmc) {
      query.reg_dwmc = {
        $regex: new RegExp(reg_dwmc, 'i')
      }
    }
    if (reg_xzxq) {
      query.reg_xzxq = reg_xzxq
    }
    if (submitter) {
      query.submitter = submitter
    }
    if (reg_status) {
      query.reg_status = reg_status
    }
    if (place) {
      query.place = place
    }
    const sort = {
      submitDate: -1
    }
    page = parseInt(page) || 1
    const limit = parseInt(pageSize) || 100
    const skip = (page - 1) * (limit)
    const data = await this.registrations.find(query).sort(sort).skip(skip).limit(limit).populate('place').populate('submitter').populate('auditor')
    const totalSize = await this.registrations.countDocuments(query)
    return {
      data,
      totalSize
    }
  }
  findOne (id) {
    return this.registrations.find({
      deleted: false,
      _id: id
    }).populate('place').populate('submitter').populate('auditor')
  }
  updateOne (id, data) {
    return this.registrations.findOneAndUpdate({
      _id: id
    }, data)
  }
  resolve (id, {
    audit_suggestion = ''
  }) {
    return this.registrations.findOneAndUpdate({
      _id: id
    }, {
      reg_status: 'resolve',
      audit_suggestion: audit_suggestion
    })
  }
  reject (id, {
    audit_suggestion = ''
  }) {
    return this.registrations.findOneAndUpdate({
      _id: id
    }, {
      reg_status: 'reject',
      audit_suggestion: audit_suggestion
    })
  }
  deleteOne (id) {
    return this.registrations.findOneAndUpdate({
      _id: id
    }, {
      deleted: true
    })
  }
  async addOne (doc) {
    // TODO check doc
    doc.reg_dwbh = doc.reg_dwlb + (doc.reg_xfxkzbh || +new Date())
    logger.info('registration created ', doc)
    return await this.registrations.create(doc)
  }
}

module.exports = RegistrationService